package com.itheima.mq;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.RecommendVideo;
import com.itheima.domain.mongo.Video;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author Guanxing
 * @date 2021/10/9
 */
@Component
public class RecommendVideoTask {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Scheduled(cron = "0/5 * * * * *")
    public void run() {
        System.out.println("开启视频推荐,正在读取redis数据加载到mongo中...");
        Set<String> keys = stringRedisTemplate.keys("QUANZI_VIDEO_RECOMMEND_*");
        if (CollectionUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                key = key.replaceAll("QUANZI_VIDEO_RECOMMEND_", "");

                //清除原来推荐的历史数据
                Query removeQuery = new Query(
                        Criteria.where("userId").is(Long.valueOf(key))
                );
                mongoTemplate.remove(removeQuery, RecommendVideo.class);


                //切割数据
                String s = stringRedisTemplate.opsForValue().get("QUANZI_VIDEO_RECOMMEND_" + key);
                String[] videoIds = s.split(",");
                //添加数据
                if (videoIds != null) {
                    for (String videoId : videoIds) {
                        RecommendVideo recommendVideo = new RecommendVideo();
                        recommendVideo.setDate(System.currentTimeMillis());
                        recommendVideo.setUserId(Long.valueOf(key));//用户id
                        recommendVideo.setVid(Long.valueOf(videoId));
                        Query query = new Query(
                                Criteria.where("vid").is(videoId)
                        );
                        Video video = mongoTemplate.findOne(query, Video.class);
                        recommendVideo.setVideoId(video.getId());
                        recommendVideo.setScore(RandomUtil.randomDouble(60, 90));

                        mongoTemplate.save(recommendVideo);
                    }
                }
            }
        }
    }
}
